<template>
  <div class="wrapper" ref="wrapper">
    <div class="scroll-content">
      <!-- 增强的下拉刷新提示容器 -->
      <div
        class="pull-down-refresh"
        v-if="isPullingDown"
        :class="{ refreshing: isPullingDown }"
      >
        <div class="refresh-content">
          <div class="loading-spinner"></div>
          <span class="refresh-text">{{ pullDownText }}</span>
        </div>
      </div>
      <!-- 瀑布流容器 -->
      <pubu :data="list" />
      <!-- 上拉加载提示 -->
      <div class="pull-up-load" :class="{ loading: isPullingUp }">
        <div class="load-content">
          <div class="loading-spinner" v-if="isPullingUp"></div>
          <span class="load-text">{{ pullUpText }}</span>
        </div>
      </div>
      <div style="height: 150px; width: 100%"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watchEffect, computed, nextTick } from "vue";
import BScroll from "@better-scroll/core";
import PullDown from "@better-scroll/pull-down";
import pubu from "./components/pubu.vue";
import PullUp from "@better-scroll/pull-up";
import { getmeteappDate } from "@/api/metapp";
import { useRoute } from "vue-router";

// 注册插件
BScroll.use(PullDown);
BScroll.use(PullUp);

const wrapper = ref<HTMLElement | null>(null);
let bs: BScroll | null = null;
// 生成随机高度（模拟图片高度）
const generateRandomHeight = () => Math.floor(Math.random() * 100) + 100;
const Route = useRoute();
const tatolref = ref(0);

// 初始数据
const list = ref<any[]>([]);
const pageNo = ref(1);
const getdata = async (id: any, pageSize: any, pageNo: any) => {
  const res = await getmeteappDate({ id, pageSize: pageSize, pageNo: pageNo });
  tatolref.value = res.data.data.paginations.total;
  list.value = [
    ...list.value,
    ...res.data.data.courses.map((item: any) => {
      return {
        id: item.id,
        text: item.text,
        height: generateRandomHeight(),
        tag: item.tag,
        imgUrl: item.imgurl,
        vidioUrl: item.vidiourl,
        name: item.name,
        likeCount: item.likecount,
      };
    }),
  ];
};

getdata(Route.params.id, 6, 1);

// 下拉状态
const isPullingDown = ref(false);
const pullDownText = ref("下拉刷新");
const pullUpText = ref("上拉加载更多");
const isPullingUp = ref(true);
const position = ref("absolute");
const top = ref("-60px");
// 清理旧数据并重置页码
const getNewData = async () => {
  return new Promise((resolve) => {
    isPullingDown.value = true;
    pullDownText.value = "正在刷新...";
    setTimeout(() => {
      pageNo.value = 1; // 重置页码
      list.value = []; // 清除旧数据
      getdata(Route.params.id, 6, pageNo.value); // 加载第一页数据
      pullDownText.value = "刷新成功";
      bs?.finishPullDown();
      bs?.refresh(); // 刷新滚动视图
      resolve(true);
    }, 1000);
  });
};

// 加载更多数据
const loadMoreData = async () => {
  return new Promise((resolve) => {
    if (list.value.length >= tatolref.value) {
      pullUpText.value = "没有更多了";
      resolve(false);
      return;
    }
    isPullingUp.value = true;
    pullUpText.value = "正在加载...";
    setTimeout(() => {
      pageNo.value++;
      getdata(Route.params.id, 6, pageNo.value);
      pullUpText.value =
        list.value.length >= tatolref.value ? "没有更多了" : "加载成功";
      bs?.finishPullUp();
      bs?.refresh(); // 刷新滚动视图
      resolve(true);
    }, 1000);
  });
};

onMounted(() => {
  // getdata();
  if (wrapper.value) {
    bs = new BScroll(wrapper.value, {
      scrollY: true,
      pullUpLoad: {
        threshold: 50,
        stop: 0,
      },
      pullDownRefresh: {
        threshold: 0,
        stop: 0, // 增加停留高度，让提示更明显
      },
      probeType: 3,
      click: true,
      taps: true,
      hasVerticalScroll: true, // 开启垂直滚动
    });

    // 下拉刷新事件
    bs.on("pullingDown", async () => {
      await getNewData();
      bs?.finishPullDown();
      pullUpText.value = "";
      bs?.refresh();
      setTimeout(() => {
        isPullingDown.value = false;
      }, 500);
    });

    // 上拉加载事件
    bs.on("pullingUp", async () => {
      await loadMoreData();
      bs?.finishPullUp();
      bs?.refresh();
      setTimeout(() => {
        isPullingUp.value = false;
      }, 500);
    });

    // 滚动时更新状态
    bs.on("scroll", (pos: { y: number }) => {
      if (pos.y >= 0) {
        position.value = "relative";
        top.value = "0px";
      }

      if (!isPullingDown.value) {
        if (pos.y > 50) {
          pullDownText.value = "释放刷新";
        } else {
          pullDownText.value = "下拉刷新";
        }
      }
    });
    // 初始化时自动刷新
    bs.refresh();
  }
});
</script>

<style scoped lang="scss">
.wrapper {
  height: 100vh;
  position: relative;
  border: 1px solid #eee;

  .scroll-content {
    min-height: 150%;
    padding-bottom: 100px; // 确保有足够的空间让 better-scroll 触发滚动
    position: relative;
  }

  .content {
    padding: 0;
    margin: 0;
    list-style: none;

    li {
      padding: 15px;
      border-bottom: 1px solid #f0f0f0;
    }
  }
  .pull-down-refresh {
    position: v-bind(position);
    width: 100%;
    top: v-bind(top);
    height: 60px;
    display: flex;
    justify-content: center;
    background-color: white;
    align-items: center;
    transition: all 0.3s;

    &.refreshing {
      background: white;
    }

    .refresh-content {
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .refresh-text {
      font-size: 14px;
      color: #666;
    }

    .loading-spinner {
      width: 20px;
      height: 20px;
      border: 2px solid #ddd;
      border-top-color: #42b983;
      border-radius: 50%;
      animation: spin 0.8s linear infinite;
    }
  }

  /* 上拉加载样式 */
  .pull-up-load {
    position: absolute;
    width: 100%;
    height: 50px;
    display: flex;
    justify-content: center;
    align-items: center;

    &.loading {
      background: white;
    }

    .load-content {
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .load-text {
      font-size: 14px;
      color: #666;
    }

    .loading-spinner {
      width: 16px;
      height: 16px;
      border: 2px solid #ddd;
      border-top-color: #42b983;
      border-radius: 50%;
      animation: spin 0.8s linear infinite;
    }
  }

  @keyframes spin {
    to {
      transform: rotate(360deg);
    }
  }
}
</style>
